﻿Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Xml


Public Class clsARInvoice

    Dim sPayDocEntry As String = String.Empty
    Dim p_oCompany As SAPbobsCOM.Company
    Dim oDICompany As SAPbobsCOM.Company
    Dim dDocTotal As Double = 0
    Dim oDataViewItemCode As DataView = Nothing

    Function ARInvoice(ByRef oDataSet As DataSet, ByRef oDICompany1 As SAPbobsCOM.Company, _
                       ByRef sErrDesc As String) As Long

        Dim sFuncName As String = String.Empty
        Dim lRetCode As Long
        Dim sDocEntry As String = String.Empty
        Dim sPayDocEntry As String = String.Empty
        Dim sTransID As String = String.Empty
        Dim sWhsCode As String = String.Empty
        Dim sPOSNumber As String = String.Empty
        Dim sProject As String = String.Empty
        Dim sOrderNo As String = String.Empty

        Dim oDataViewHeader As DataView = Nothing
        Dim oDataViewLine As DataView = Nothing
        Dim oDataViewPayment As DataView = Nothing
        Dim oDataViewSetMeal As DataView = Nothing
        Dim oDTItemCodes As DataTable = New DataTable

        Dim oDTDistinctHeader As DataTable = Nothing
        Dim oDTDistSetMeal As DataTable = Nothing

        Dim dIncomeDate As Date
        Dim sDiscItemCodes() As String = New String() {"HDUTY", "HSPOI", "HMKTN", "HFLUS", ""}
        Dim bIsDiscItem As Boolean = False
        Dim sDiscLineItem As String = String.Empty
        Dim sProductCode As String = String.Empty
        Dim sQuery As String = String.Empty
        Dim dPQty As Double = 0.0
        Dim dGrossTotalAmount As Double = 0.0
        Dim dSalesQty As Double = 0.0
        Dim sCOGSAccountCode As String = String.Empty
        Dim sVatGroup As String = String.Empty

        Dim oARInvoice As SAPbobsCOM.Documents


        Try
            sFuncName = "ARInvoice()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            oDataViewHeader = oDataSet.Tables(0).DefaultView
            oDataViewLine = oDataSet.Tables(1).DefaultView
            oDataViewSetMeal = oDataSet.Tables(2).DefaultView
            oDataViewPayment = oDataSet.Tables(3).DefaultView

            sQuery = "select ItemCode,VatGourpSa from OITM where SellItem ='Y'"

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Get_DataTable()", sFuncName)
            oDTItemCodes = Get_DataTable(sQuery, P_sSAPConString, sErrDesc)


            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling ConnectToTargetCompany()", sFuncName)
            If ConnectToTargetCompany(p_oCompany, sErrDesc) <> RTN_SUCCESS Then Throw New ArgumentException(sErrDesc)

            oDataViewItemCode = oDTItemCodes.DefaultView

            oDTDistinctHeader = oDataViewHeader.Table.DefaultView.ToTable(True, "TransID")

            For IntHeader As Integer = 0 To oDTDistinctHeader.Rows.Count - 1

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Assign the Company", sFuncName)

                oDICompany = p_oCompany

                oDICompany.XmlExportType = SAPbobsCOM.BoXmlExportTypes.xet_ExportImportMode

                If oDICompany.InTransaction = False Then oDICompany.StartTransaction()

                oARInvoice = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts)

                oARInvoice.ReserveInvoice = SAPbobsCOM.BoYesNoEnum.tYES

                sTransID = oDTDistinctHeader.Rows(IntHeader).Item("TransID").ToString.Trim
                dIncomeDate = Convert.ToDateTime(oDataViewHeader.Item(IntHeader).Row("BusinessDate").ToString)
                sPOSNumber = CStr(oDataViewHeader.Item(IntHeader).Row("POSNumber").ToString.Trim)
                sWhsCode = CStr(oDataViewHeader.Item(IntHeader).Row("Outlet").ToString.Trim)
                sProject = CStr(oDataViewHeader.Item(IntHeader).Row("Project").ToString.Trim)
                sOrderNo = String.Empty

                dGrossTotalAmount = (CDbl(oDataViewHeader.Item(IntHeader).Row("GrossAmount").ToString.Trim) - CDbl(oDataViewHeader.Item(IntHeader).Row("Rounding").ToString.Trim))

                oARInvoice.CardCode = sCardCode
                oARInvoice.DocDate = dIncomeDate
                oARInvoice.DocDueDate = dIncomeDate
                oARInvoice.TaxDate = dIncomeDate
                oARInvoice.UserFields.Fields.Item("U_POSNo").Value = sPOSNumber
                oARInvoice.UserFields.Fields.Item("U_Covers").Value = CStr(oDataViewHeader.Item(IntHeader).Row("Covers").ToString)
                oARInvoice.UserFields.Fields.Item("U_Outlet").Value = sWhsCode
                oARInvoice.Project = sProject
                oARInvoice.NumAtCard = sWhsCode & " - " & sPOSNumber

                oARInvoice.DocObjectCode = SAPbobsCOM.BoObjectTypes.oInvoices

                oARInvoice.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Items

                oDataViewLine.RowFilter = "TransID = '" & sTransID & "'"

                For IntRow As Integer = 0 To oDataViewLine.Count - 1

                    If (oDataViewLine.Item(IntRow).Row("SetMealCode").ToString.Trim() IsNot Nothing AndAlso oDataViewLine.Item(IntRow).Row("SetMealCode").ToString.Trim() <> String.Empty) And CDbl(oDataViewLine.Item(IntRow).Row("GrossAmount").ToString) = 0.0 Then Continue For

                    sProductCode = oDataViewLine.Item(IntRow).Row("ProductCode").ToString.Trim

                    For I As Integer = 0 To sDiscItemCodes.Length - 1
                        If sDiscItemCodes(I) = sProductCode Then
                            GoTo DiscProductCode
                        End If
                    Next

                    bIsDiscItem = False

                    If CStr(oDataViewLine.Item(IntRow).Row("DiscountCode").ToString.Trim) <> String.Empty Then
                        sDiscLineItem = oDataViewLine.Item(IntRow).Row("DiscountCode").ToString.Trim

                        For I As Integer = 0 To sDiscItemCodes.Length - 1
                            If sDiscItemCodes(I) = sDiscLineItem Then
                                bIsDiscItem = True
                                Exit For
                            End If
                        Next


                        If bIsDiscItem = True Then
                            Dim sFiledName As String = String.Empty

                            If sDiscLineItem = "HDUTY" Then
                                sFiledName = "U_DutyCOGS"
                            ElseIf sDiscLineItem = "HSPOI" Then
                                sFiledName = "U_SpoilsCOGS"
                            ElseIf sDiscLineItem = "HMKTN" Then
                                sFiledName = "U_MktngCOGS"
                            ElseIf sDiscLineItem = "HFLUS" Then
                                sFiledName = "U_FlushCOGS"
                            End If

                            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling GetSingleValue(). Reference Line : " & IntRow, sFuncName)

                            oARInvoice.Lines.COGSAccountCode = GetSingleValue("SELECT T1.[" & sFiledName & "] FROM OITM T0 INNER JOIN OITB T1 " & _
                                                                              " ON T0.[ItmsGrpCod] = T1.[ItmsGrpCod] WHERE T0.[ItemCode] ='" & sProductCode & "' " _
                                                                              , oDICompany, sErrDesc)
                            oARInvoice.Lines.LineTotal = 0
                        Else
                            oARInvoice.Lines.Price = CDbl(oDataViewLine.Item(IntRow).Row("Price").ToString)
                            oARInvoice.Lines.LineTotal = CDbl(oDataViewLine.Item(IntRow).Row("GrossAmount").ToString)
                        End If
                    Else
                        oARInvoice.Lines.Price = CDbl(oDataViewLine.Item(IntRow).Row("Price").ToString)
                        oARInvoice.Lines.LineTotal = CDbl(oDataViewLine.Item(IntRow).Row("GrossAmount").ToString)
                    End If

                    oARInvoice.Lines.ItemCode = sProductCode
                    oARInvoice.Lines.Quantity = oDataViewLine.Item(IntRow).Row("Quantity").ToString
                    oARInvoice.Lines.WarehouseCode = sWhsCode
                    oARInvoice.Lines.ProjectCode = sProject

                    oDataViewItemCode.RowFilter = "ItemCode ='" & sProductCode & "'"
                    sVatGroup = oDataViewItemCode(0)("VatGourpSa").ToString()

                    oARInvoice.Lines.VatGroup = sVatGroup

                    ' ''  oARInvoice.Lines.VatGroup = GetSingleValue("select VatGourpSa  from OITM where ItemCode ='" & sProductCode & "' " _
                    '                                                          , oDICompany, sErrDesc)
                    oARInvoice.Lines.COGSCostingCode = sWhsCode
                    oARInvoice.Lines.CostingCode = sWhsCode
                    oARInvoice.Lines.UserFields.Fields.Item("U_POSNo").Value = CStr(sPOSNumber)
                    oARInvoice.Lines.UserFields.Fields.Item("U_DiscCode").Value = CStr(oDataViewLine.Item(IntRow).Row("DiscountCode").ToString.Trim)
                    oARInvoice.Lines.UserFields.Fields.Item("U_SetMealCode").Value = CStr(oDataViewLine.Item(IntRow).Row("SetMealCode").ToString.Trim)
                    oARInvoice.Lines.UserFields.Fields.Item("U_DiscItem").Value = CStr(oDataViewLine.Item(IntRow).Row("DiscountedItem").ToString.Trim)
                    oARInvoice.Lines.Add()
                    ' End If
DiscProductCode:

                Next

                'Started SET MEAL Details:


                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Start SET MEAL DETAILS", sFuncName)

                oDTDistSetMeal = oDataViewLine.Table.DefaultView.ToTable(True, "SetMealCode")

                For IntSetMeal As Integer = 0 To oDTDistSetMeal.Rows.Count - 1


                    If String.IsNullOrWhiteSpace(oDTDistSetMeal.Rows(IntSetMeal).Item("SetMealCode").ToString.Trim) Then Continue For

                    If String.IsNullOrEmpty(oDTDistSetMeal.Rows(IntSetMeal).Item("SetMealCode").ToString.Trim) Then Continue For


                    oDataViewLine.RowFilter = "SetMealCode = '" & oDTDistSetMeal.Rows(IntSetMeal).Item("SetMealCode").ToString.Trim & "' And TransID = '" & sTransID & "'"

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling GetSingleValue(). Reference Line : " & IntSetMeal, sFuncName)

                    Dim dAmount As Double = GetSingleValue("select SetMealGross from " & P_sStagingDBName & "..SalesTransDETSetMeal " & _
                                                           " where SetMealCode ='" & oDataViewLine.Item(IntSetMeal).Row("SetMealCode").ToString.Trim & "' " & _
                                                           " and HeaderID='" & sTransID & "' ", oDICompany, sErrDesc)
                    Dim dSingleAmount As Double = 0.0
                    Dim sFinalAmount As Double = 0.0
                    Dim dMealCodeQty(50) As Double

                    Array.Clear(dMealCodeQty, 0, dMealCodeQty.Length - 1)

                    For IntSetMealRow As Integer = 0 To oDataViewLine.Count - 1

                        dSingleAmount = CDbl(oDataViewLine.Item(IntSetMealRow).Row("Quantity").ToString.Trim) *
                       CDbl(GetSingleValue(" select isnull(Price,0) from " & P_sSAPDBName & "..ITM1 T0 INNER JOIN " & P_sSAPDBName & "..OPLN T1 on T0.PriceList =T1.ListNum  " & _
                                       " where T0.ItemCode ='" & CStr(oDataViewLine.Item(IntSetMealRow).Row("ProductCode").ToString.Trim) & "' and " & _
                                       " T1.ListName ='" & P_sPriceListName & "' ", oDICompany, sErrDesc))
                        sFinalAmount += dSingleAmount

                        dMealCodeQty(IntSetMealRow) = dSingleAmount

                    Next

                    For IntSetMealRow As Integer = 0 To oDataViewLine.Count - 1

                        sProductCode = oDataViewLine.Item(IntSetMealRow).Row("ProductCode").ToString.Trim()

                        oARInvoice.Lines.ItemCode = sProductCode
                        oARInvoice.Lines.Quantity = CDbl(oDataViewLine.Item(IntSetMealRow).Row("Quantity").ToString.Trim())
                        oARInvoice.Lines.LineTotal = (dMealCodeQty(IntSetMealRow) / sFinalAmount) * dAmount
                        oARInvoice.Lines.WarehouseCode = sWhsCode
                        oARInvoice.Lines.ProjectCode = sProject

                        oDataViewItemCode.RowFilter = "ItemCode ='" & sProductCode & "'"
                        sVatGroup = oDataViewItemCode(0)("VatGourpSa").ToString()

                        oARInvoice.Lines.VatGroup = sVatGroup

                        oARInvoice.Lines.COGSCostingCode = sWhsCode
                        oARInvoice.Lines.CostingCode = sWhsCode
                        oARInvoice.Lines.UserFields.Fields.Item("U_POSNo").Value = CStr(sPOSNumber)
                        oARInvoice.Lines.UserFields.Fields.Item("U_DiscCode").Value = CStr(oDataViewLine.Item(IntSetMealRow).Row("DiscountCode").ToString.Trim)
                        oARInvoice.Lines.UserFields.Fields.Item("U_SetMealCode").Value = CStr(oDataViewLine.Item(IntSetMealRow).Row("SetMealCode").ToString.Trim)
                        oARInvoice.Lines.UserFields.Fields.Item("U_DiscItem").Value = CStr(oDataViewLine.Item(IntSetMealRow).Row("DiscountedItem").ToString.Trim)
                        oARInvoice.Lines.Add()

                    Next

                Next

                If CDbl(oDataViewHeader.Item(IntHeader).Row("ServiceCharge").ToString) <> 0 Then

                    oARInvoice.Lines.ItemCode = sServiceItem
                    oARInvoice.Lines.Quantity = 1
                    oARInvoice.Lines.Price = CDbl(oDataViewHeader.Item(IntHeader).Row("ServiceCharge").ToString)
                    oARInvoice.Lines.UserFields.Fields.Item("U_POSNo").Value = CStr(sPOSNumber)

                    oDataViewItemCode.RowFilter = "ItemCode ='" & sServiceItem & "'"
                    sVatGroup = oDataViewItemCode(0)("VatGourpSa").ToString()

                    oARInvoice.Lines.VatGroup = sVatGroup

                    oARInvoice.Lines.ProjectCode = sProject
                    oARInvoice.Lines.WarehouseCode = sWhsCode
                    oARInvoice.Lines.COGSCostingCode = sWhsCode
                    oARInvoice.Lines.CostingCode = sWhsCode
                    oARInvoice.Lines.Add()
                End If

                If CDbl(oDataViewHeader.Item(IntHeader).Row("ExcessAmount").ToString) <> 0 Then
                    oARInvoice.Lines.ItemCode = sExcessItem
                    oARInvoice.Lines.Quantity = 1
                    oARInvoice.Lines.Price = CDbl(oDataViewHeader.Item(IntHeader).Row("ExcessAmount").ToString)
                    oARInvoice.Lines.UserFields.Fields.Item("U_POSNo").Value = CStr(sPOSNumber)

                    oDataViewItemCode.RowFilter = "ItemCode ='" & sExcessItem & "'"
                    sVatGroup = oDataViewItemCode(0)("VatGourpSa").ToString()

                    oARInvoice.Lines.VatGroup = sVatGroup

                    oARInvoice.Lines.ProjectCode = sProject
                    oARInvoice.Lines.WarehouseCode = sWhsCode
                    oARInvoice.Lines.COGSCostingCode = sWhsCode
                    oARInvoice.Lines.CostingCode = sWhsCode
                    oARInvoice.Lines.Add()
                End If

                If CDbl(oDataViewHeader.Item(IntHeader).Row("TipsAmount").ToString) <> 0 Then
                    oARInvoice.Lines.ItemCode = sTipsItem
                    oARInvoice.Lines.Quantity = 1
                    oARInvoice.Lines.Price = CDbl(oDataViewHeader.Item(IntHeader).Row("TipsAmount").ToString)
                    oARInvoice.Lines.UserFields.Fields.Item("U_POSNo").Value = CStr(sPOSNumber)

                    oDataViewItemCode.RowFilter = "ItemCode ='" & sTipsItem & "'"
                    sVatGroup = oDataViewItemCode(0)("VatGourpSa").ToString()

                    oARInvoice.Lines.VatGroup = sVatGroup

                    oARInvoice.Lines.ProjectCode = sProject
                    oARInvoice.Lines.WarehouseCode = sWhsCode
                    oARInvoice.Lines.COGSCostingCode = sWhsCode
                    oARInvoice.Lines.CostingCode = sWhsCode
                    oARInvoice.Lines.Add()
                End If

                lRetCode = oARInvoice.Add()

                If lRetCode <> 0 Then
                    sErrDesc = oDICompany.GetLastErrorDescription
                    Call WriteToLogFile(sErrDesc, sFuncName)

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Update_Status() ", sFuncName)
                    Update_Status(sTransID, sErrDesc, "FAIL", "", "SalesTransHDR")

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Rollback the Transaction ", sFuncName)
                    If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting the Company and Release the Object ", sFuncName)
                    'oDICompany.Disconnect()
                    'oDICompany = Nothing
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oARInvoice)
                    oARInvoice = Nothing
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)

                Else
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oARInvoice)
                    oARInvoice = Nothing
                    oDICompany.GetNewObjectCode(sDocEntry)

                    'If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS. Reference : " & sDocEntry, sFuncName)


                    ' Update the COGS Account Code for the BOM Child Items

                    '*********************************************Update the COGS Account Code Start *************************************************

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Update_Draft()", sFuncName)

                    If Update_Draft(oDICompany, sDocEntry, dGrossTotalAmount, sPOSNumber, sWhsCode, sProject, sErrDesc) <> RTN_SUCCESS Then

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Update_Status()", sFuncName)
                        Update_Status(sTransID, sErrDesc, "FAIL", "", "SalesTransHDR")

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Rollback the Transaction Reference POSNumber : " & sPOSNumber, sFuncName)
                        If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting the Company and Release the Object ", sFuncName)
                        'oDICompany.Disconnect()
                        'oDICompany = Nothing
                        'GC.Collect()
                        Continue For

                    End If

                    Dim sDraftKeyNew As String = String.Empty

                    oDICompany.GetNewObjectCode(sDraftKeyNew) 'AR Reserve Invoice for Create the DO Draft aas well Incoming Payment


                    '*************************** DO Draft Starting ************************************************************************************

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling CopyDocument()", sFuncName)

                    Dim oCopyMarketingDoc As clsCopyMarketingDocument = New clsCopyMarketingDocument

                    If oCopyMarketingDoc.CopyDocument(SAPbobsCOM.BoObjectTypes.oInvoices, sDraftKeyNew, _
                                                     SAPbobsCOM.BoObjectTypes.oDeliveryNotes, oDICompany, sErrDesc, True) <> RTN_SUCCESS Then

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Rollback the Transaction Reference POSNumber : " & sPOSNumber, sFuncName)
                        If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
                        Update_Status(sTransID, sErrDesc, "FAIL", "", "SalesTransHDR")

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting the Company and Release the Object ", sFuncName)
                        'oDICompany.Disconnect()
                        'oDICompany = Nothing
                        'oARInvoice = Nothing

                        'GC.Collect()

                        Continue For

                    End If

                    '****************************************** DO Draft  Finished ************************************************************************************

                    If dDocTotal = 0 Then

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Committed the Transaction Reference POSNumber : " & sPOSNumber, sFuncName)
                        If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Update_Status() ", sFuncName)
                        Update_Status(sTransID, sErrDesc, "SUCCESS", sDraftKeyNew, "SalesTransHDR")
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Committed the Transaction Reference Num : " & sPayDocEntry & " POSNumber : " & sPOSNumber, sFuncName)

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting the Company and Release the Object ", sFuncName)
                        'oDICompany.Disconnect()
                        'oDICompany = Nothing
                        'GC.Collect()
                        oARInvoice = Nothing

                        Continue For

                    End If


                    '************************************ Incoming Payment Started ************************************************************************************

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Incoming Payment. Reference : " & sDocEntry, sFuncName)

                    If AR_IncomingPayment(oDataViewPayment, oDICompany, sDraftKeyNew, sTransID, dIncomeDate, sPOSNumber _
                                       , sOrderNo, sWhsCode, sCardCode, sProject, sErrDesc) <> RTN_SUCCESS Then


                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Update_Status() ", sFuncName)
                        Update_Status(sTransID, sErrDesc, "FAIL", "", "SalesTransHDR")

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Rollback the SAP Transaction ", sFuncName)
                        If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting the Company and Release the Object ", sFuncName)
                        'oDICompany.Disconnect()
                        'oDICompany = Nothing
                        'GC.Collect()
                        oARInvoice = Nothing

                        Continue For


                    End If

                    '*************************** Incoming Payment Finished ************************************************************************************
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Update_Status() ", sFuncName)

                    sErrDesc = ""

                    Update_Status(sTransID, sErrDesc, "SUCCESS", sDraftKeyNew, "SalesTransHDR")

                    If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Committed the Transaction Reference POSNumber : " & sPOSNumber, sFuncName)

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting the Company and Release the Object ", sFuncName)
                    'oDICompany.Disconnect()
                    'oDICompany = Nothing
                    'GC.Collect()

                End If
            Next


            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS ", sFuncName)

            Return RTN_SUCCESS


        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Update_Status() Function" & sPOSNumber, sFuncName)

            Update_Status(sTransID, sErrDesc, "FAIL", "", "SalesTransHDR")

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Rollback the Transaction. POS Number : " & sPOSNumber, sFuncName)
            If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting the Company and Release the Object ", sFuncName)
            p_oCompany.Disconnect()
            oDICompany.Disconnect()
            oDICompany = Nothing
            p_oCompany = Nothing

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Return RTN_ERROR

        End Try
    End Function

    Function AR_IncomingPayment(ByRef oDataViewPayment As DataView, ByVal oDICompany As SAPbobsCOM.Company, _
                                 ByVal sDocEntry As String, ByVal sTransID As String, ByVal dIncomeDate As Date, _
                                 ByVal sPOSNumber As String, ByVal sOrderNo As String, ByVal sWhsCode As String, _
                                ByVal sCardCode As String, ByVal sProject As String, ByRef sErrDesc As String) As Long

        Dim sFuncName As String = String.Empty
        Dim lRetCode As Long
        Dim oIncomingPaymentDraft As SAPbobsCOM.Payments
        Dim oIncomingPayment As SAPbobsCOM.Payments
        Try
            sFuncName = "AR_IncomingPayment"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            oIncomingPayment = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPaymentsDrafts)

            'Dim oIncomingPayment As SAPbobsCOM.Payments = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oIncomingPayments)
            Dim sCreditCard As String = String.Empty

            oIncomingPayment.DocType = SAPbobsCOM.BoRcptTypes.rCustomer
            oIncomingPayment.CardCode = CStr(sCardCode)
            oIncomingPayment.DocDate = dIncomeDate
            oIncomingPayment.DueDate = dIncomeDate
            oIncomingPayment.TaxDate = dIncomeDate
            oIncomingPayment.DocObjectCode = SAPbobsCOM.BoPaymentsObjectType.bopot_IncomingPayments


            If sDocEntry <> "" Then
                oIncomingPayment.Invoices.DocEntry = sDocEntry
                oIncomingPayment.Invoices.InvoiceType = SAPbobsCOM.BoRcptInvTypes.it_Invoice
            End If


            oIncomingPayment.Invoices.Add()

            oDataViewPayment.RowFilter = "TransID = '" & sTransID & "'"

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Trans ID : " & sTransID & " Row Count : " & oDataViewPayment.Count, sFuncName)

            For IntPayment As Integer = 0 To oDataViewPayment.Count - 1

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling GetSingleValue() for CreditCard ", sFuncName)

                sCreditCard = GetSingleValue("select CreditCard  from OCRC where CardName =(select Name from [@TENDER] " &
                                             " where U_TenderCode ='" & oDataViewPayment.Item(IntPayment).Row("PaymentCode").ToString.Trim & "') ", _
                                                                          oDICompany, sErrDesc)
                ' If sCreditCard = 14 Then Continue For

                oIncomingPayment.CreditCards.CreditCard = sCreditCard

                oIncomingPayment.CreditCards.CreditType = SAPbobsCOM.BoRcptCredTypes.cr_Regular

                oIncomingPayment.CreditCards.CardValidUntil = "01/12/9999"
                oIncomingPayment.CreditCards.CreditCardNumber = oDataViewPayment.Item(IntPayment).Row("CrCardNum").ToString.Trim
                oIncomingPayment.CreditCards.VoucherNum = sWhsCode & "-" & CDate(dIncomeDate).ToString("yyMMdd") & "-" & sPOSNumber

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Amount : " & CDbl(oDataViewPayment.Item(IntPayment).Row("PaymentAmount").ToString.Trim), sFuncName)

                oIncomingPayment.CreditCards.CreditSum = CDbl(oDataViewPayment.Item(IntPayment).Row("PaymentAmount").ToString.Trim)
                oIncomingPayment.CreditCards.Add()

                sOrderNo = CStr(oDataViewPayment.Item(IntPayment).Row("OrderNo").ToString.Trim)
            Next

            oIncomingPayment.UserFields.Fields.Item("U_WHSCode").Value = sWhsCode
            oIncomingPayment.UserFields.Fields.Item("U_POSNo").Value = sPOSNumber
            oIncomingPayment.UserFields.Fields.Item("U_SONo").Value = sOrderNo
            oIncomingPayment.ProjectCode = sProject

            oIncomingPayment.CashSum = 0

            lRetCode = oIncomingPayment.Add()

            If lRetCode <> 0 Then
                sErrDesc = oDICompany.GetLastErrorDescription
                Call WriteToLogFile(sErrDesc, sFuncName)
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Incoming Payment Completed with ERROR", sFuncName)

                AR_IncomingPayment = RTN_ERROR
            Else

                oDICompany.GetNewObjectCode(sPayDocEntry)

                oIncomingPaymentDraft = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPaymentsDrafts)

                oIncomingPaymentDraft.GetByKey(sPayDocEntry)

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Converting Payment Draft to Document ", sFuncName)

                lRetCode = oIncomingPaymentDraft.SaveDraftToDocument()

                If lRetCode <> 0 Then
                    sErrDesc = oDICompany.GetLastErrorDescription
                    Call WriteToLogFile(sErrDesc, sFuncName)
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Incoming Payment Completed with ERROR Draft key : " & sPayDocEntry, sFuncName)
                    AR_IncomingPayment = RTN_ERROR
                Else
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Incoming Payment Completed with SUCCESS.", sFuncName)
                    AR_IncomingPayment = RTN_SUCCESS

                End If

            End If

        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            AR_IncomingPayment = RTN_ERROR

        Finally
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Releasing the Objects", sFuncName)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oIncomingPayment)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oIncomingPaymentDraft)
            oIncomingPayment = Nothing
            oIncomingPaymentDraft = Nothing
        End Try
    End Function

    Function ARInvoice_DataSet(ByVal sConnectionString As String) As DataSet

        Dim oDataSet As DataSet
        Dim oDataTable, oDTCondition As DataTable
        Dim sQuery As String = String.Empty
        Dim sFuncName As String = String.Empty
        Dim oConnection As SqlConnection
        Dim oSQLCommand As SqlCommand
        Dim oSQLAdapter As SqlDataAdapter = New SqlDataAdapter

        Try
            sFuncName = "ARInvoice_DataSet()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting function", sFuncName)
            oDataSet = New DataSet

            sQuery = "select ID [TransID] ,U_Outlet [Outlet] ,U_POSNo[POSNumber] ,BusinessDate ,isnull(GrossAmount,0) [GrossAmount] ,isnull(ServiceCharge,0) [ServiceCharge] " & _
                " ,isnull(GST,0) [GST] , isnull(Rounding,0) [Rounding] ,isnull(ExcessAmount,0) [ExcessAmount] ,isnull(TipsAmount,0) [TipsAmount] " & _
                " ,isnull(Covers,0)[Covers] ,RevenueCenterName [Project]  from SalesTransHDR where isnull(Status,'')='' and isnull(ReceiveDate,'')='' order by BusinessDate"

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Header Query : " & sQuery, sFuncName)

            oConnection = New SqlConnection(sConnectionString)

            If (oConnection.State = ConnectionState.Closed) Then
                oConnection.Open()
            End If

            oDataTable = New DataTable
            oSQLCommand = New SqlCommand(sQuery, oConnection)
            oSQLAdapter.SelectCommand = oSQLCommand
            oSQLCommand.CommandTimeout = 0
            oSQLAdapter.Fill(oDataTable)
            oDataSet.Tables.Add(oDataTable)


            If oDataSet.Tables(0).Rows.Count > 0 Then

                'Get a DocEntry for Read the Lines Level Values Based on Respective DocEntry

                sQuery = ""
                sQuery = "declare  @diststring as varchar(max)"
                sQuery += vbCrLf + "select   @diststring=coalesce(@diststring+ ''', ''','')+convert(varchar,ID)from SalesTransHDR where isnull(Status,'')='' and isnull(ReceiveDate,'')='' order by BusinessDate"
                sQuery += vbCrLf + "select  ''''+@diststring+ '''' as TransID "

                oDTCondition = New DataTable
                oSQLCommand = New SqlCommand(sQuery, oConnection)
                oSQLAdapter.SelectCommand = oSQLCommand
                oSQLCommand.CommandTimeout = 0

                oSQLAdapter.Fill(oDTCondition)


                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Condition Query : " & sQuery, sFuncName)
                'To Get Get a Line Level Data's 

                sQuery = ""
                sQuery += vbCrLf + "select HeaderID [TransID] ,U_Outlet [Outlet] ,U_POSNo [POSNumber] ,ProductCode ,isnull(Price,0) [Price] " & _
                    " ,isnull(Quantity,0) [Quantity] ,isnull(GrossAmount,0) [GrossAmount] ,DiscountCode ,SetMealCode ,RevenueCenterName [Project] " & _
                    " ,ProductSetCode,DiscountedItem  from SalesTransDET where HeaderID in (" & oDTCondition.Rows(0)("TransID").ToString & ")  "

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Line Detail Query : " & sQuery, sFuncName)

                oDataTable = New DataTable
                oSQLCommand = New SqlCommand(sQuery, oConnection)
                oSQLAdapter.SelectCommand = oSQLCommand
                oSQLCommand.CommandTimeout = 0
                oSQLAdapter.Fill(oDataTable)
                oDataSet.Tables.Add(oDataTable)
                'To Get the SET Meal Details:
                sQuery = ""
                sQuery += vbCrLf + "select HeaderID [TransID],SetMealCode ,SetMealPrice ,SetMealGross ,SetMealName ,QuantitySold ,U_Outlet [Outlet] " & _
                    " ,U_POSNo [POSNumber] ,BusinessDate  from SalesTransDETSetMeal  where HeaderID in (" & oDTCondition.Rows(0)("TransID").ToString & ")  "

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("SET Mal Detail Query : " & sQuery, sFuncName)

                oDataTable = New DataTable
                oSQLCommand = New SqlCommand(sQuery, oConnection)
                oSQLAdapter.SelectCommand = oSQLCommand
                oSQLCommand.CommandTimeout = 0
                oSQLAdapter.Fill(oDataTable)
                oDataSet.Tables.Add(oDataTable)
                'To Get the Payment Details:
                sQuery = ""
                sQuery += vbCrLf + "select HeaderID[TransID] ,U_Outlet [Outlet] ,U_POSNo [POSNumber] ,OrderNo ,RevenueCenterName [Project] ,BusinessDate " & _
                    " ,PaymentCode ,isnull(PaymentAmount,0) [PaymentAmount] ,CrCardNum  from PaymentTrans  where HeaderID in (" & oDTCondition.Rows(0)("TransID").ToString & ")  "

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Payment Details Query : " & sQuery, sFuncName)

                oDataTable = New DataTable
                oSQLCommand = New SqlCommand(sQuery, oConnection)
                oSQLAdapter.SelectCommand = oSQLCommand
                oSQLCommand.CommandTimeout = 0
                oSQLAdapter.Fill(oDataTable)
                oDataSet.Tables.Add(oDataTable)

                oSQLAdapter.Dispose()
                oSQLCommand.Dispose()
                oConnection.Close()

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                Return oDataSet
            Else
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                Return Nothing
            End If
        Catch ex As Exception
            Call WriteToLogFile(ex.Message, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Return Nothing
        End Try
    End Function

    Public Function GetSingleValue(ByVal Query As String, ByRef p_oDICompany As SAPbobsCOM.Company, ByRef sErrDesc As String) As String

        ' ***********************************************************************************
        '   Function   :    GetSingleValue()
        '   Purpose    :    This function is handles - Return single value based on Query
        '   Parameters :    ByVal Query As String
        '                       sDate = Passing Query 
        '                   ByRef oCompany As SAPbobsCOM.Company
        '                       oCompany = Passing the Company which has been connected
        '                   ByRef sErrDesc As String
        '                       sErrDesc=Error Description to be returned to calling function
        '   Author     :    SRINIVASAN
        '   Date       :    15/08/2014 
        '   Change     :   
        '                   
        ' ***********************************************************************************

        Dim sFuncName As String = String.Empty

        Try
            sFuncName = "GetSingleValue()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Query : " & Query, sFuncName)

            Dim objRS As SAPbobsCOM.Recordset = p_oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset)
            objRS.DoQuery(Query)
            If objRS.RecordCount > 0 Then
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                GetSingleValue = RTN_SUCCESS

                Return objRS.Fields.Item(0).Value.ToString
            End If
        Catch ex As Exception
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            WriteToLogFile(ex.Message, sFuncName, sLogFolderPath)
            GetSingleValue = RTN_SUCCESS
            Return ""
        End Try
        Return Nothing
    End Function

    Public Function Get_Recordset(ByVal Query As String, ByRef p_oDICompany As SAPbobsCOM.Company, ByRef sErrDesc As String) As SAPbobsCOM.Recordset

        ' ***********************************************************************************
        '   Function   :    Get_Recordset()
        '   Purpose    :    This function is handles - Return Recordset value based on Query
        '   Parameters :    ByVal Query As String
        '                       sDate = Passing Query 
        '                   ByRef oCompany As SAPbobsCOM.Company
        '                       oCompany = Passing the Company which has been connected
        '                   ByRef sErrDesc As String
        '                       sErrDesc=Error Description to be returned to calling function
        '   Author     :    SRINIVASAN
        '   Date       :    15/08/2014 
        '   Change     :   
        '                   
        ' ***********************************************************************************

        Dim sFuncName As String = String.Empty

        Try
            sFuncName = "Get_Recordset()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Query : " & Query, sFuncName)

            Dim objRS As SAPbobsCOM.Recordset = p_oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset)
            objRS.DoQuery(Query)
            'If objRS.RecordCount > 0 Then
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
            Return objRS
            ' End If
        Catch ex As Exception
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            WriteToLogFile(ex.Message, sFuncName, sLogFolderPath)
            Return Nothing
        End Try
        Return Nothing
    End Function

    Public Sub Update_Status(ByVal sHeaderID As String, ByVal sMessage As String, ByVal sStatus As String, ByVal sDocEntry As String, ByVal sTableName As String)

        Dim sFuncName As String = String.Empty
        Dim oDataTable As DataTable = New DataTable
        Dim oConnection As SqlConnection
        Dim oSQLCommand As SqlCommand
        Dim oSQLAdapter As SqlDataAdapter = New SqlDataAdapter
        Dim sQuery As String = String.Empty


        Try
            sFuncName = "Update_Status()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting function", sFuncName)

            sMessage = Replace(sMessage, "'", " ")

            sQuery = "Update " & sTableName & " set ARDocEntry='" & sDocEntry & "', ReceiveDate =GETDATE(),ErrMsg ='" & sMessage & "' ,Status ='" & sStatus & "' where ID='" & sHeaderID & "' "

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Query : " & sQuery, sFuncName)



            oConnection = New SqlConnection(P_sConString)


            If (oConnection.State = ConnectionState.Closed) Then
                oConnection.Open()
            End If

            oSQLCommand = New SqlCommand(sQuery, oConnection)
            oSQLAdapter.SelectCommand = oSQLCommand
            oSQLCommand.CommandTimeout = 0
            oSQLAdapter.Fill(oDataTable)
            oSQLAdapter.Dispose()
            oSQLCommand.Dispose()
            oConnection.Close()

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)

        Catch ex As Exception
            Call WriteToLogFile(ex.Message, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
        End Try
    End Sub

    Function Update_Draft(ByRef oDICompany As SAPbobsCOM.Company, ByVal sDraftDocNum As String, ByVal dGrossTotal As Double, _
                          ByVal sPOSNumber As String, ByVal sWhsCode As String, ByVal sProjectCode As String, ByRef sErrDesc As String) As Long

        Dim lRetCode As Long
        Dim iCount As Integer = 0
        Dim sFuncName As String = String.Empty
        Dim dDiffAmount As Double = 0.0
        Dim sDraftNew As String = String.Empty
        Dim oDTDraftDetails As DataTable = New DataTable
        Dim oDTBOMCount As DataTable = New DataTable
        Dim sQuery As String = String.Empty
        Dim sTreeType As String = String.Empty
        Dim sCOGSAcctCode As String = String.Empty
        Dim sWarehouse As String = String.Empty
        Dim oDraftAftUpdate As SAPbobsCOM.Documents = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts)
        Dim oDraftNew As SAPbobsCOM.Documents = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts)
        Dim oRS As SAPbobsCOM.Recordset = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset)
        Dim sVatGroup As String = String.Empty

        Dim bLoopExist As Boolean = False


        Try

            sFuncName = "Update_Draft()"

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting function", sFuncName)

            sQuery = "select T0.[ItemCode],T0.[U_POSNo],T0.[Project],T0.[CogsAcct],T0.[WhsCode],T0.[LineNum],T0.[TreeType] from DRF1 T0 where DocEntry='" & sDraftDocNum & "'"

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Executing the Query, Query String : " & sQuery, sFuncName)

            oRS.DoQuery(sQuery)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling ConvertRecordset()", sFuncName)

            oDTDraftDetails = ConvertRecordset(oRS, sErrDesc)


            ''oDTDraftDetails = Get_DataTable(sQuery, P_sSAPConString, sErrDesc)

            oDraftAftUpdate.GetByKey(sDraftDocNum)

            For IDraftRow As Integer = 0 To oDTDraftDetails.Rows.Count - 1

                If bLoopExist = True Then Exit For

                sCOGSAcctCode = oDTDraftDetails.Rows.Item(IDraftRow)("CogsAcct").ToString().Trim()

                sQuery = " WITH BOM (Code, Level, TreeType) AS ( SELECT T0.Code, 0 as Level, T2.TreeType  FROM dbo.OITT T0 inner join OITM T2 on T0.Code = T2.ItemCode " & _
                        " WHERE T0.Code = '" & oDTDraftDetails.Rows.Item(IDraftRow)("ItemCode").ToString().Trim() & "' UNION ALL   SELECT T1.Code , Level +1 , T2.TreeType   FROM " & _
                        " dbo.ITT1 AS T1 inner join OITM T2  on T1.Code = T2.ItemCode JOIN BOM ON T1.Father = BOM.Code AND BOM.TreeType ='S' ) " & _
                        " SELECT COUNT(Code) FROM BOM  WHERE Code NOT IN (SELECT Code FROM OITT WHERE TreeType ='S') OPTION (MAXRECURSION 99) "

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Executing the Query, Query String : " & sQuery, sFuncName)

                oRS.DoQuery(sQuery)

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling ConvertRecordset()", sFuncName)

                oDTBOMCount = ConvertRecordset(oRS, sErrDesc)

                iCount = oDTBOMCount.Rows(0)(0).ToString()

                If iCount = 0 Then Continue For

                For iRowCount As Integer = IDraftRow + 1 To IDraftRow + iCount
                    oDraftAftUpdate.Lines.SetCurrentLine(iRowCount)

                    ''If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Header Loop : " & IDraftRow & "Line Loop :" & iRowCount, sFuncName)

                    oDraftAftUpdate.Lines.WarehouseCode = sWhsCode
                    oDraftAftUpdate.Lines.COGSAccountCode = sCOGSAcctCode
                    oDraftAftUpdate.Lines.COGSCostingCode = sWhsCode
                    oDraftAftUpdate.Lines.CostingCode = sWhsCode
                    oDraftAftUpdate.Lines.ProjectCode = sProjectCode
                    oDraftAftUpdate.Lines.UserFields.Fields.Item("U_POSNo").Value = CStr(sPOSNumber)

                    'oDraftAftUpdate.Lines.Add()

                    bLoopExist = True

                    Exit For

                Next
                IDraftRow = IDraftRow + iCount

            Next

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Before Update the Draft With Update Draft", sFuncName)

            lRetCode = oDraftAftUpdate.Update()

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("After Update the Draft. Return Value : " & lRetCode, sFuncName)

            If lRetCode <> 0 Then
                sErrDesc = oDICompany.GetLastErrorDescription
                Throw New ArgumentException(sErrDesc)
            Else

                ''  oDraftAftUpdate.GetByKey(sDraftDocNum)

                dDocTotal = oDraftAftUpdate.DocTotal
                ' Dim dTax As Double = oDraftAftUpdate.VatSum
                dDiffAmount = (dGrossTotal - dDocTotal)

                If dDiffAmount <> 0 Then
                    oDraftAftUpdate.Lines.Add()
                    oDraftAftUpdate.Lines.SetCurrentLine(oDraftAftUpdate.Lines.Count - 1)
                    oDraftAftUpdate.Lines.ItemCode = sGSTItem

                    If dDiffAmount < 0 Then
                        oDraftAftUpdate.Lines.Quantity = -1
                        oDraftAftUpdate.Lines.UnitPrice = Replace(dDiffAmount, "-", "")
                    Else
                        oDraftAftUpdate.Lines.Quantity = 1
                        oDraftAftUpdate.Lines.LineTotal = dDiffAmount
                    End If
                    oDraftAftUpdate.Lines.UserFields.Fields.Item("U_POSNo").Value = CStr(sPOSNumber)

                    oDataViewItemCode.RowFilter = "ItemCode ='" & sGSTItem & "'"
                    sVatGroup = oDataViewItemCode(0)("VatGourpSa").ToString()

                    oDraftAftUpdate.Lines.VatGroup = sVatGroup

                    oDraftAftUpdate.Lines.ProjectCode = sProjectCode
                    oDraftAftUpdate.Lines.WarehouseCode = sWhsCode
                    oDraftAftUpdate.Lines.COGSCostingCode = sWhsCode
                    oDraftAftUpdate.Lines.CostingCode = sWhsCode

                End If

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Before Updating the Differnece Amount ", sFuncName)

                lRetCode = oDraftAftUpdate.Update()

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("After Updated the Differnece Amount ", sFuncName)

                If lRetCode <> 0 Then Throw New ArgumentException(oDICompany.GetLastErrorDescription)

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling SaveDraftToDocument()", sFuncName)

                sFuncName = "SaveDraftToDocument"

                oDICompany.GetNewObjectCode(sDraftNew)

                oDraftNew.GetByKey(sDraftNew)

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Before Convert SaveDraftToDocument()", sFuncName)

                lRetCode = oDraftNew.SaveDraftToDocument()

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("After Convert SaveDraftToDocument() Return Value : " & lRetCode, sFuncName)

                If lRetCode <> 0 Then Throw New ArgumentException(oDICompany.GetLastErrorDescription)

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS SaveDraftToDocument()", sFuncName)

            End If

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)


            Update_Draft = RTN_SUCCESS

        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Update_Draft = RTN_ERROR
        Finally

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Releasing the Objects", sFuncName)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oDraftNew)
            oDraftNew = Nothing
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oDraftAftUpdate)
            oDraftAftUpdate = Nothing

        End Try

    End Function

    Function AddNewDraft_BasedonExistingDraft(ByVal sDocKkey As String, ByVal dDiffAmount As Double, ByRef oDICompany As SAPbobsCOM.Company, ByRef sErrDesc As String)

        Dim lRetCode As Long
        Dim sFuncName As String = String.Empty
        Dim sDraftNew As String = String.Empty

        Try

            sFuncName = "AddNewDraft_BasedonExistingDraft()"

            Dim oDraftOld As SAPbobsCOM.Documents = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts)
            Dim oDraftNew As SAPbobsCOM.Documents = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts)
            Dim oDraftNew1 As SAPbobsCOM.Documents = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts)

            oDraftOld.GetByKey(sDocKkey)

            oDraftNew.ReserveInvoice = SAPbobsCOM.BoYesNoEnum.tYES
            oDraftNew.DocObjectCode = SAPbobsCOM.BoObjectTypes.oInvoices

            oDraftNew.CardCode = oDraftOld.CardCode
            oDraftNew.DocDate = oDraftOld.DocDate
            oDraftNew.DocDueDate = oDraftOld.DocDueDate
            oDraftNew.TaxDate = oDraftOld.TaxDate
            oDraftNew.UserFields.Fields.Item("U_POSNo").Value = oDraftOld.UserFields.Fields.Item("U_POSNo").Value
            oDraftNew.UserFields.Fields.Item("U_Covers").Value = oDraftOld.UserFields.Fields.Item("U_Covers").Value
            oDraftNew.UserFields.Fields.Item("U_Outlet").Value = oDraftOld.UserFields.Fields.Item("U_Outlet").Value
            oDraftNew.Project = oDraftOld.Project
            oDraftNew.NumAtCard = oDraftOld.NumAtCard
            oDraftNew.Comments = "Testing"

            For iRow As Integer = 0 To oDraftOld.Lines.Count - 1

                oDraftOld.Lines.SetCurrentLine(iRow)

                oDraftNew.Lines.ItemCode = oDraftOld.Lines.ItemCode
                oDraftNew.Lines.Quantity = oDraftOld.Lines.Quantity
                oDraftNew.Lines.LineTotal = oDraftOld.Lines.LineTotal
                oDraftNew.Lines.WarehouseCode = oDraftOld.Lines.WarehouseCode
                oDraftNew.Lines.ProjectCode = oDraftOld.Lines.ProjectCode
                oDraftNew.Lines.TaxCode = oDraftOld.Lines.TaxCode
                oDraftNew.Lines.COGSCostingCode = oDraftOld.Lines.COGSCostingCode
                oDraftNew.Lines.CostingCode = oDraftOld.Lines.CostingCode
                oDraftNew.Lines.UserFields.Fields.Item("U_POSNo").Value = oDraftOld.Lines.UserFields.Fields.Item("U_POSNo").Value
                oDraftNew.Lines.UserFields.Fields.Item("U_DiscCode").Value = oDraftOld.Lines.UserFields.Fields.Item("U_DiscCode").Value
                oDraftNew.Lines.UserFields.Fields.Item("U_SetMealCode").Value = oDraftOld.Lines.UserFields.Fields.Item("U_SetMealCode").Value
                oDraftNew.Lines.UserFields.Fields.Item("U_DiscItem").Value = oDraftOld.Lines.UserFields.Fields.Item("U_DiscItem").Value
                oDraftNew.Lines.Add()

            Next

            If dDiffAmount <> 0 Then

                oDraftNew.Lines.ItemCode = sGSTItem
                If dDiffAmount < 0 Then

                    oDraftNew.Lines.Quantity = -1
                    oDraftNew.Lines.UnitPrice = Replace(dDiffAmount, "-", "")
                Else
                    oDraftNew.Lines.Quantity = 1
                    oDraftNew.Lines.LineTotal = dDiffAmount
                End If
                oDraftNew.Lines.UserFields.Fields.Item("U_POSNo").Value = oDraftOld.Lines.UserFields.Fields.Item("U_POSNo").Value
                oDraftNew.Lines.TaxCode = "ZO"
                oDraftNew.Lines.ProjectCode = oDraftOld.Project
                oDraftNew.Lines.WarehouseCode = oDraftOld.Lines.WarehouseCode
                oDraftNew.Lines.COGSCostingCode = oDraftOld.Lines.WarehouseCode
                oDraftNew.Lines.CostingCode = oDraftOld.Lines.WarehouseCode

                oDraftNew.Lines.Add()

            End If

            lRetCode = oDraftNew.Add()

            If lRetCode <> 0 Then Throw New ArgumentException(oDICompany.GetLastErrorDescription)

            oDICompany.GetNewObjectCode(sDraftNew)

            'If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Remove() for Old Draft Document", sFuncName)

            'lRetCode = oDraftOld.Remove()

            'If lRetCode <> 0 Then Throw New ArgumentException(oDICompany.GetLastErrorDescription)

            'If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed With SUCCESS Remove() for Old Draft Document", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling SaveDraftToDocument()", sFuncName)

            sFuncName = "SaveDraftToDocument"

            Dim oReserveInv As SAPbobsCOM.Documents = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInvoices)

            oDraftNew1.GetByKey(sDraftNew)

            'oDraftNew1.SaveXML("E:\Drft.xml")

            'oReserveInv.Browser.ReadXml("E:\Drft.xml", 0)

            'lRetCode = oReserveInv.Add()

            'Kill("E:\Drft.xml")

            lRetCode = oDraftNew1.SaveDraftToDocument()

            If lRetCode <> 0 Then Throw New ArgumentException(oDICompany.GetLastErrorDescription)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS SaveDraftToDocument()", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting function", sFuncName)

            AddNewDraft_BasedonExistingDraft = RTN_SUCCESS

        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            AddNewDraft_BasedonExistingDraft = RTN_ERROR
        End Try
    End Function

    Function Document_Creation(ByVal oBaseType As SAPbobsCOM.BoObjectTypes, ByVal oTargetType As SAPbobsCOM.BoObjectTypes _
                               , ByRef oBaseComp As SAPbobsCOM.Company, ByRef oTarComp As SAPbobsCOM.Company _
                               , ByVal sDocEntry As String, ByRef IsDraft As Boolean) As Long
        Try
            Dim lRetCode As Long
            Dim oBaseDoc As SAPbobsCOM.Documents = oBaseComp.GetBusinessObject(oBaseType)
            Dim oTarDoc As SAPbobsCOM.Documents
            Dim sFuncName As String = String.Empty

            sFuncName = "Document_Creation()"

            If oBaseDoc.GetByKey(sDocEntry) Then

                If IsDraft = False Then
                    oTarDoc = oTarComp.GetBusinessObject(oTargetType)
                Else
                    oTarDoc = oTarComp.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts)
                    oTarDoc.DocObjectCode = oTargetType
                End If

                oTarDoc.CardCode = oBaseDoc.CardCode
                oTarDoc.DocDate = oBaseDoc.DocDate
                oTarDoc.TaxDate = oBaseDoc.TaxDate
                oTarDoc.DocDueDate = oBaseDoc.DocDueDate
                oTarDoc.UserFields.Fields.Item("U_POSNo").Value = oBaseDoc.UserFields.Fields.Item("U_POSNo").Value
                oTarDoc.UserFields.Fields.Item("U_Covers").Value = oBaseDoc.UserFields.Fields.Item("U_Covers").Value
                oTarDoc.Project = oBaseDoc.Project
                oTarDoc.NumAtCard = oBaseDoc.NumAtCard
                oTarDoc.DocTotal = oBaseDoc.DocTotal

                Dim count As Integer = oBaseDoc.Lines.Count - 1

                Dim oTargetLines As SAPbobsCOM.Document_Lines = oTarDoc.Lines

                For i As Integer = 0 To count
                    If i <> 0 Then
                        oTargetLines.Add()
                    End If
                    oBaseDoc.Lines.SetCurrentLine(i)

                    oTargetLines.ItemCode = oBaseDoc.Lines.ItemCode
                    oTargetLines.Quantity = oBaseDoc.Lines.Quantity
                    oTargetLines.LineTotal = oBaseDoc.Lines.LineTotal
                    oTargetLines.WarehouseCode = oBaseDoc.Lines.WarehouseCode
                    oTargetLines.ProjectCode = oBaseDoc.Lines.ProjectCode
                    oTargetLines.TaxCode = oBaseDoc.Lines.TaxCode
                    oTargetLines.AccountCode = oBaseDoc.Lines.AccountCode
                    oTargetLines.COGSCostingCode = oBaseDoc.Lines.COGSCostingCode
                    oTargetLines.UserFields.Fields.Item("U_POSNo").Value = oBaseDoc.Lines.UserFields.Fields.Item("U_POSNo").Value
                    oTargetLines.UserFields.Fields.Item("U_DiscCode").Value = oBaseDoc.Lines.UserFields.Fields.Item("U_DiscCode").Value
                    oTargetLines.UserFields.Fields.Item("U_SetMealCode").Value = oBaseDoc.Lines.UserFields.Fields.Item("U_SetMealCode").Value
                    oTargetLines.UserFields.Fields.Item("U_DiscItem").Value = oBaseDoc.Lines.UserFields.Fields.Item("U_DiscItem").Value

                Next

                lRetCode = oTarDoc.Add()

                If lRetCode <> 0 Then
                    Call WriteToLogFile(oTarComp.GetLastErrorDescription, sFuncName)
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
                Else
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                End If

            Else
                Return RTN_SUCCESS
            End If

            Return RTN_SUCCESS
        Catch ex As Exception
            Return RTN_ERROR
        End Try
    End Function

    Function Get_DataTable(ByVal sQueryString As String, ByVal sConnString As String, ByRef sErrDesc As String) As DataTable

        Dim sFuncName As String = String.Empty
        Dim oDataTable As DataTable = New DataTable
        Dim oConnection As SqlConnection
        Dim oSQLCommand As SqlCommand
        Dim oSQLAdapter As SqlDataAdapter = New SqlDataAdapter


        Try
            sFuncName = "Get_DataTable()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Query : " & sQueryString, sFuncName)

            oConnection = New SqlConnection(sConnString)


            If (oConnection.State = ConnectionState.Closed) Then
                oConnection.Open()
            End If


            oSQLCommand = New SqlCommand(sQueryString, oConnection)
            oSQLAdapter.SelectCommand = oSQLCommand
            oSQLCommand.CommandTimeout = 0
            oSQLAdapter.Fill(oDataTable)
            oSQLAdapter.Dispose()
            oSQLCommand.Dispose()
            oConnection.Close()

            Get_DataTable = oDataTable

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)

        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Get_DataTable = Nothing
        End Try

    End Function

    Public Function ConvertRecordset(ByVal SAPRecordset As SAPbobsCOM.Recordset, ByRef sErrDesc As String) As DataTable

        '\ This function will take an SAP recordset from the SAPbobsCOM library and convert it to a more
        '\ easily used ADO.NET datatable which can be used for data binding much easier.
        Dim sFuncName As String = String.Empty
        Dim dtTable As New DataTable
        Dim NewCol As DataColumn
        Dim NewRow As DataRow
        Dim ColCount As Integer

        Try
            sFuncName = "ConvertRecordset()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting function", sFuncName)

            For ColCount = 0 To SAPRecordset.Fields.Count - 1
                NewCol = New DataColumn(SAPRecordset.Fields.Item(ColCount).Name)
                dtTable.Columns.Add(NewCol)
            Next

            Do Until SAPRecordset.EoF

                NewRow = dtTable.NewRow
                'populate each column in the row we're creating
                For ColCount = 0 To SAPRecordset.Fields.Count - 1

                    NewRow.Item(SAPRecordset.Fields.Item(ColCount).Name) = SAPRecordset.Fields.Item(ColCount).Value

                Next

                'Add the row to the datatable
                dtTable.Rows.Add(NewRow)


                SAPRecordset.MoveNext()
            Loop

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
            Return dtTable

        Catch ex As Exception

            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Return Nothing

        End Try

    End Function

    Public Function ConnectToTargetCompany(ByRef oCompany As SAPbobsCOM.Company, _
                                          ByRef sErrDesc As String) As Long

        ' **********************************************************************************
        '   Function    :   ConnectToTargetCompany()
        '   Purpose     :   This function will be providing to proceed the connectivity of 
        '                   using SAP DIAPI function
        '               
        '   Parameters  :   ByRef oCompany As SAPbobsCOM.Company
        '                       oCompany =  set the SAP DI Company Object
        '                   ByRef sErrDesc AS String 
        '                       sErrDesc = Error Description to be returned to calling function
        '               
        '   Return      :   0 - FAILURE
        '                   1 - SUCCESS
        '   Author      :   JOHN
        '   Date        :   MAY 2013 21
        ' **********************************************************************************

        Dim sFuncName As String = String.Empty
        Dim iRetValue As Integer = -1
        Dim iErrCode As Integer = -1
        Dim sSQL As String = String.Empty
        Dim oDs As New DataSet

        Try
            sFuncName = "ConnectToTargetCompany()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Initializing the Company Object", sFuncName)

            oCompany = New SAPbobsCOM.Company

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Assigning the representing database name", sFuncName)

            oCompany.Server = p_sServerName
            oCompany.LicenseServer = p_sLicServerName
            oCompany.DbUserName = p_sDBUserName
            oCompany.DbPassword = p_sDBPassword
            oCompany.language = SAPbobsCOM.BoSuppLangs.ln_English
            oCompany.UseTrusted = False

            If p_sSQLType = 2012 Then
                oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012
            ElseIf p_sSQLType = 2008 Then
                oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2008
            End If

            oCompany.CompanyDB = p_sDataBaseName
            oCompany.UserName = p_sSAPUserName
            oCompany.Password = p_sSAPPassword

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Connecting to the Company Database.", sFuncName)

            iRetValue = oCompany.Connect()

            If iRetValue <> 0 Then
                oCompany.GetLastError(iErrCode, sErrDesc)

                sErrDesc = String.Format("Connection to Database ({0}) {1} {2} {3}", _
                    oCompany.CompanyDB, System.Environment.NewLine, _
                                vbTab, sErrDesc)

                Throw New ArgumentException(sErrDesc)
            End If

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
            ConnectToTargetCompany = RTN_SUCCESS
        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(ex.Message, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            ConnectToTargetCompany = RTN_ERROR
        End Try
    End Function

    Private Enum EnumofXMLFiles
        XMLDDT
        XMLINVDraft
        XMLInvoice
    End Enum

    Private ReadOnly XMLINVDraftName As String = "InvoiceDraft.xml"
    Private ReadOnly XMLInvoiceName As String = "InvoiceDraftToDef.xml"
    Private ReadOnly XMLINVDraftFullPath As String = "C:Temp" & XMLINVDraftName
    Private ReadOnly XMLInvoiceFullPath As String = "C:Temp" & XMLInvoiceName

    Public Function CreateDocumentFromDraft(ByRef oDICompany As SAPbobsCOM.Company, ByVal sDraftEntry As String) As String
        Dim oRPS As SAPbobsCOM.Documents = Nothing
        Dim oNFSE As SAPbobsCOM.Documents = Nothing
        Dim CodErro As Integer = 0
        Dim MsgErro As String = ""
        Try
            oRPS = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts)
            oNFSE = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInvoices)
            oRPS.GetByKey(sDraftEntry)
            oDICompany.XmlExportType = SAPbobsCOM.BoXmlExportTypes.xet_ExportImportMode
            oRPS.SaveXML(XMLINVDraftFullPath)
            oNFSE.CardCode = sCardCode
            'Modifico il file XML             
            ModifyXML(XMLINVDraftFullPath, EnumofXMLFiles.XMLINVDraft)
            ' oNFSE.Browser.ReadXml(XmlRPS, 0)
            oNFSE = oDICompany.GetBusinessObjectFromXML(XMLInvoiceFullPath, 0)
            CodErro = oNFSE.Add()
            If (CodErro = 0) Then
                Dim NewObjectKey As String = oDICompany.GetNewObjectKey()
                ''  MessageBox.Show("Doc creato con successo! (" & NewObjectKey & ")")
                Return NewObjectKey
            Else
                oDICompany.GetLastError(CodErro, MsgErro)
                ''  MessageBox.Show("errore (" & CodErro & "): " & MsgErro)
            End If
        Catch ex As Exception
            '' MessageBox.Show(ex.Message)
            Return ""
        End Try
    End Function

    Private Sub UpdateNode(ByRef XMLNode As Xml.XmlNode, ByVal NameNode As String, ByVal value As String)
        Dim XMLTempNode As Xml.XmlNode = Nothing
        Try
            XMLTempNode = XMLNode.Item(NameNode)
            If XMLTempNode Is Nothing Then 'Se è Nothing significa che il nodo figlio cercato non esiste. Procedo quindi a crearlo

                Dim elem As Xml.XmlElement = XMLNode.OwnerDocument.CreateElement(NameNode)
                'elem.InnerText = value ' Potrei già attribuire il valore ma lo faccio successivamente                
                'Add the node to the document.                 
                XMLNode.AppendChild(elem)
            End If
            'A questo punto il nodo esiste certamente e quindi procedo con il suo aggiornamento            
            XMLNode = XMLNode.Item(NameNode) 'Mi posiziono sul nodo figlio in questione            
            XMLNode.InnerText = value 'Impongo il valore         
        Catch ex As Exception
            ''  MsgBox.Show(ex.Message)
        Finally
            XMLNode = XMLNode.ParentNode 'Torno al padre           
            XMLTempNode = Nothing
        End Try
    End Sub

    Private Sub DeleteNode(ByRef XMLNode As Xml.XmlNode, ByVal NameNode As String)
        Dim XMLTempNode As Xml.XmlNode = Nothing
        Try
            XMLTempNode = XMLNode.Item(NameNode)
            If XMLTempNode IsNot Nothing Then
                'Se è Nothing significa che il nodo figlio cercato non esiste. Procedo quindi solo se esiste.                 
                'Effettuo l'eliminazione del nodo figlio in esame                   
                XMLNode.RemoveChild(XMLNode.Item(NameNode))
            End If
        Catch ex As Exception
            '' MsgBox.Show(ex.Message)
        Finally
            XMLTempNode = Nothing
        End Try
    End Sub

    ''' <summary>     ''' Procedura demandata alla modifica dei vari file XML esportati al fine di creare i corrispondenti     
    ''' ''' per importazione.    
    '''  ''' </summary>     ''' <param name="XMLFilePath">Percorso completo del file XML esportato da utilizzare come base di elaborazione</param>     ''' <param name="XMLFileSource">Tipo di file XML; determina come va interpretato.</param>     ''' <remarks></remarks>    
    ''' 

    Private Sub ModifyXML(ByVal XMLFilePath As String, ByRef XMLFileSource As EnumofXMLFiles)
        Dim XMLDoc As New Xml.XmlDocument
        Dim XMLElement As Xml.XmlElement = Nothing
        Dim XMLNode As Xml.XmlNode = Nothing
        Dim InvLineNum As Long = 0
        Dim DDTLineNum As String = "0"
        Try
            Select Case XMLFileSource
                Case EnumofXMLFiles.XMLINVDraft                     'Apertura del file XML                    
                    XMLDoc.Load(XMLFilePath)                     'Posizionamento                      
                    XMLNode = XMLDoc.LastChild
                    XMLNode = XMLNode.Item("BO")
                    '------------------------------                    
                    'Gestione informazioni generali                     
                    '------------------------------                     
                    XMLNode = XMLNode.Item("AdmInfo")
                    UpdateNode(XMLNode, "Object", "13")
                    'Impongo che il documento sia una fattura in definitivo                     
                    '---------------------------------------------                     
                    'Gestione righe                     
                    '---------------------------------------------                     
                    XMLNode = XMLNode.ParentNode 'Passo a BO                     
                    XMLNode = XMLNode.Item("Document_Lines")
                    'Passo direttamente a Document_Lines                      
                    'Questa sezione si ripete per tutte le righe presenti nel documento

                    'For Each XMLNodeCicle As Xml.XmlNode In XMLNode.ChildNodes
                    '    DeleteNode(XMLNodeCicle, "COGSAccountCode")
                    '    'Elimino il nodo                     
                    'Next

                    'Effettuo il salvataggio del documento XML                    
                    XMLDoc.Save(Replace(XMLFilePath, XMLINVDraftName, XMLInvoiceName))
            End Select
            XMLDoc = Nothing
        Catch ex As Exception
            '' MessageBox.Show(ex.Message)
        End Try
    End Sub

End Class
